<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\MissingValue;

class BaseResource extends JsonResource
{

    /**
     * BaseResource constructor.
     * @param $resource
     */
    public function __construct($resource)
    {
        parent::__construct($resource);

        $isIncludeLoadedBound = app()->bound('include_load');
        $request = request();
        if (!$isIncludeLoadedBound && $request->has('include')) {
            get_include($resource);
            // 注册
            app()->instance('include_load', true);
        }
    }

    /**
     * 重写collection方法 自动预加载关联npm
     * @param mixed $resource
     * @return AnonymousResourceCollection
     */
    public static function collection($resource)
    {
        if ($resource instanceof MissingValue) {
            return new AnonymousResourceCollection($resource, static::class);
        }
        $isIncludeLoadedBound = app()->bound('include_load');
        $request = request();
        if (!$isIncludeLoadedBound && $request->has('include')) {
            $resource = get_include($resource);
            app()->instance('include_load', true);
        }
        return new AnonymousResourceCollection($resource, static::class);
    }


}
